package com.jrtc.service.impl;

import com.jrtc.base.config.constants.PublicConstants;
import com.jrtc.base.entity.bo.Remind;
import com.jrtc.base.entity.vo.RemindVo;
import com.jrtc.dao.RemindDao;
import com.jrtc.service.RemindService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 提醒表(Remind)表服务实现类
 */
@Service("remindService")
public class RemindServiceImpl implements RemindService {
    @Resource
    private RemindDao remindDao;

    /**
     * 设置提醒
     */
    @Override
    public int insertRemind(RemindVo remindVo, Integer patientId) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("HH:mm");
        if (remindVo != null){
            Remind remind = new Remind();
            if (remindVo.getMorningOrAfternoon() != null && !remindVo.getMorningOrAfternoon().equals("")){
                if (remindVo.getMorningOrAfternoon().equals(PublicConstants.MorningOrAfternoon.AM.getValue())){
                    remind.setRemindTime(remindVo.getRemindTime());
                }
                else if (remindVo.getMorningOrAfternoon().equals(PublicConstants.MorningOrAfternoon.PM.getValue())){
                    long time = format.parse(remindVo.getRemindTime()).getTime();
                    time = time + (12 * 60 * 60 * 1000);
                    Date date = new Date();
                    date.setTime(time);
                    remind.setRemindTime(format.format(date));
                }
                else {
                    throw new Exception("提醒时间出错了");
                }
            }
            else {
                throw new Exception("提醒时间相关参数不能为空");
            }

            remind.setIsrepeat(remindVo.getIsrepeat());

            String week = null;
            if (remindVo.getWeekDayList() != null && remindVo.getWeekDayList().size() > 0){
                for (int i = 0 ; i < remindVo.getWeekDayList().size() ; i++) {
                    if (i == 0){
                        week = remindVo.getWeekDayList().get(i);
                    }
                    else {
                        week = week + "," + remindVo.getWeekDayList().get(i);
                    }
                }
            }
            else {
                throw new Exception("每周几提醒不能为空");
            }

            remind.setWeekday(week);
            remind.setPatientId(patientId);
            remind.setStatus(remindVo.getStatus());

            int insertRemind = remindDao.insert(remind);
            if (insertRemind > 0){
                return insertRemind;
            }
            else {
                throw new Exception("设置时间失败");
            }
        }
        else {
            throw new Exception("缺少必要参数");
        }
    }
}